import router from "@/router";
import {getResquest} from "@/utils/api";

export const initMenu = (router,store) => {
    if(store.state.routes>0){
        return;
    }
    getResquest('/system/menu/getMenus').then(data=>{
        //console.log(data.data.records);
        if(data){
            //格式化路由数据
            let fmtRoutes = formatRoutes(data.data.records);
            //添加到路由
            //console.log(fmtRoutes);
            //废弃的动态路由函数
            //router.addRoutes(fmtRoutes);
            //router.matcher = new router().matcher;
            router.addRoute(...fmtRoutes);
            //保存在vuex
            store.commit('initRoutes',fmtRoutes);
        }
    })
}

export const formatRoutes = (routes) => {
    let fmtRoutes = [];
    routes.forEach(router=>{
        let{
            menuId,
            url,
            menuName,
            perms,
            menuType,
            icon,
            children
        } = router;
        if(children && children instanceof Array){
            //递归
            children = formatRoutes(children);
        }
        let fmRouter = {
            index:menuId,
            path:url,
            name:menuName,
            icon:icon,
            menu:menuType,
            children:children,
            component:() => import ('@/views/Test1.vue')
        }
        fmtRoutes.push(fmRouter);
    });
    //console.log(fmtRoutes);
    return fmtRoutes;
}